package com.example.user.login

import android.graphics.Color
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.mvvm.BaseViewActivity
import com.example.lib_base.room.AppDbUtils
import com.example.user.R
import com.example.user.databinding.ActivityLoginBinding
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

@Route(path = "/user/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initData() {
        viewModel.loginSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                SPUtils.getInstance().put("token",it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                AppDbUtils.getAppDb().getUserDao().insert(it.data)
                val query = AppDbUtils.getAppDb().getUserDao().query(it.data.phone)
                ToastUtils.showLong(query.toString())
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }
        }
        viewModel.loginFail.observe(this){
            ToastUtils.showLong(it)
        }
        binding.url = "https://www.xunjietupian.com/wp-content/uploads/2022/03/image3-6.png"
        val list = mutableListOf(
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/a272fcefed804cf2b1e6785d5662c29ejqjxha0eow.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/fb364676ea364297b7441638f9e0f557dckg4t2rds.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/3a395df3d79a40a08cbc938c35e2dc35b84sujo2yn.png"
        )
        binding.bannerurl = list
    }

    override fun initView() {
        binding.btnLogin.setOnClickListener {

            val etPhone = binding.etPhone.text.toString()
            val etPwd = binding.etPwd.text.toString()
            if(etPhone.isEmpty()||etPwd.isEmpty()){
                ToastUtils.showLong("用户名和密码均不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileExact(etPhone)){
                ToastUtils.showLong("用户名格式不正确，应该为手机号")
                return@setOnClickListener
            }
            if(!RegexUtils.isMatch("^[\\w]{6,8}$",etPwd)){
                ToastUtils.showLong("密码格式不正确，应该是6-8的数字字母下划线组合")
                return@setOnClickListener
            }
            viewModel.login(binding.etPhone.text.toString(),binding.etPwd.text.toString())
        }
        //点击快速登录 跳转到 验证码登录界面
        binding.tvGologincode.setOnClickListener {
            ARouter.getInstance().build("/user/LoginCodeActivity").navigation()
        }
        //实现底部富文本，点击弹出对话框，点击同意 框选中  点击不同意 框不选中
        val stringBuilder = SpannableStringBuilder(binding.fwb.text.toString())
        stringBuilder.setSpan(ForegroundColorSpan(Color.RED),0,2,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        val clickableSpan = object :ClickableSpan(){
            override fun onClick(widget: View) {
               showWindow("这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策这是用户政策")
            }
        }
        stringBuilder.setSpan(clickableSpan,7,13,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        val clickableSpan2 = object :ClickableSpan(){
            override fun onClick(widget: View) {
                showWindow("隐私政策")
            }
        }
        stringBuilder.setSpan(clickableSpan2,14,19,SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE)
        binding.fwb.movementMethod = LinkMovementMethod.getInstance()
        binding.fwb.text = stringBuilder

        //默认登录按钮不可用 ，当复选框被选中时，登录可用
        binding.btnLogin.isEnabled = false
        //当复选框被选中时，登录可用  监听复选框的状态
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            //isChecked  代表的是 当前cb的选中状态
            binding.btnLogin.isEnabled = isChecked
        }

        //实现方法1
        binding.ff1.setOnClickListener {
            //构建一个集合
            lifecycleScope.launch {
                val list = mutableListOf(1,2,3,4,5)
                //构建冷流
                val flow = flow {
                    list.forEach {
                        emit(it)
                        kotlinx.coroutines.delay(2000)
                    }
                }.buffer()
                flow.collect{
                    println("接收到的数据是$it")
                }
            }
        }
        //实现方法2
        binding.ff2.setOnClickListener {
            val channel = Channel<Int>()

            lifecycleScope.launch {
                channel.send(10)
                channel.send(20)
                channel.send(30)
                channel.close()
            }

            lifecycleScope.launch {
                for (i in channel){
                    println("接收到的数据是$i")
                }
            }
            val highFunc = highFunc {
                "测试高阶函数"
            }
            println(highFunc)
        }

    }

    private fun showWindow(s: String) {
        AlertDialog.Builder(this)
            .setTitle("提示")
            .setMessage(s)
            .setNegativeButton("不同意"){
                a,b->
                binding.cb.isChecked = false
            }
            .setPositiveButton("同意"){
                a,b->
                binding.cb.isChecked = true
            }
            .show()
    }

    fun highFunc(func:()->String):String{
        return "这是一个高阶函数返回的结果${func()}"
    }

    override fun getViewModel(): Class<LoginViewModel> = LoginViewModel::class.java

    override fun getLayout(): Int = R.layout.activity_login

}